#!/usr/bin/env bash
# 将 Spring Boot Jar 部署成 Linux service 并启动
# Maven 打包时，确保配置了 <executable>true</executable>
jarFile="$1"
if [ -z "$jarFile" ]; then
  jarFile=$(find . -maxdepth 1 -name "*.jar" | head -n 1)
elif [ ! -f "$jarFile" ]; then
  echo "File not found: $jarFile"
  exit 1
fi
jarFile="$(basename "$jarFile")"

serviceName="$2"
if [ -z "$serviceName" ]; then
  serviceName="${jarFile%.jar*}"
fi

serviceFile="/etc/systemd/system/${serviceName}.service"
fullJarPath=$(pwd)/$jarFile
chmod +x "$fullJarPath"
if [ ! -f "${jarFile%.jar*}.conf" ]; then
  if [ -n "$JAVA_HOME" ]; then
    javaHome="$JAVA_HOME"
  else
    # shellcheck disable=SC2046
    javaHome=$(readlink -f $(which java) | sed "s:bin/java::")
  fi
  if [ -n "$javaHome" ]; then
    echo "JAVA_HOME=$javaHome" | cat >"${jarFile%.jar*}.conf"
  else
    touch "${jarFile%.jar*}.conf"
  fi
fi
if [ ! -f "$serviceFile" ]; then
  echo "init service: ${serviceName}"
  echo "[Unit]
Description=${serviceName}
After=syslog.target

[Service]
User=$USER
Group=$USER
ExecStart=${fullJarPath}
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target" | cat >/etc/systemd/system/"${serviceName}".service

  echo "enable service: ${serviceName}"
  systemctl enable "${serviceName}".service
  echo "start service: ${serviceName}"
  systemctl start "${serviceName}".service
else
  echo "restart service: ${serviceName}"
  systemctl restart "${serviceName}".service
fi